package com.example.dllo.baidumusic.main;
/*
                   _ooOoo_
                  o8888888o
                  88" . "88
                  (| -_- |)
                  O\  =  /O
               ____/`---'\____
             .'  \\|     |//  `.
            /  \\|||  :  |||//  \
           /  _||||| -:- |||||-  \
           |   | \\\  -  /// |   |
           | \_|  ''\---/''  |   |
           \  .-\__  `-`  ___/-. /
         ___`. .'  /--.--\  `. . __
      ."" '<  `.___\_<|>_/___.'  >'"".
     | | :  `- \`.;`\ _ /`;.`/ - ` : | |
     \  \ `-.   \_ __\ /__ _/   .-` /  /
======`-.____`-.___\_____/___.-`____.-'======
                   `=---='
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
         佛祖保佑       永无BUG
*/

import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.example.dllo.baidumusic.R;
import com.example.dllo.baidumusic.adapter.ListPopAdapter;
import com.example.dllo.baidumusic.bean.MusicBean;
import com.example.dllo.baidumusic.bean.MusicBeanListBean;
import com.example.dllo.baidumusic.events.AskState;
import com.example.dllo.baidumusic.events.MusicListEvent;
import com.example.dllo.baidumusic.events.NextEvent;
import com.example.dllo.baidumusic.nettool.BaseActivity;
import com.example.dllo.baidumusic.service.PlayService;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

/**
 * Created by dllo on 16/8/18.
 */
public class NewActivity extends BaseActivity {
    private ImageView singPic;
    private TextView singName;
    private TextView singerName;
    private SeekBar seekBar;
    private CheckBox stop;
    private LinearLayout linearLayout;
    private ImageButton leibiao;
    private ImageButton next;
    private static FragmentManager fragmentManager;
    private MusicBean musicBean;
    private List<MusicBean> musicBeanList;
    private ServiceConnection conn = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            musicBinder = (PlayService.MusicBinder) service;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };
    private PlayService.MusicBinder musicBinder;

    @Override
    protected int setLayout() {
        return R.layout.activity_new;
    }

    @Override
    protected void initView() {
        singPic = bindView(R.id.play_sing_pic);
        seekBar = bindView(R.id.paly_seekbar);
        stop = bindView(R.id.music_libary_paly);
        singName = bindView(R.id.play_sing_name);
        singName.setHorizontallyScrolling(true);
        singName.setFocusable(true);
        singerName = bindView(R.id.play_singer_name);
        singerName.setHorizontallyScrolling(true);
        singerName.setFocusable(true);
        linearLayout = bindView(R.id.main_linerlayout);
        leibiao = bindView(R.id.play_liebiao);
        next = bindView(R.id.paly_next);

        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (fromUser) {
                    musicBinder.seekTo(progress);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });

        stop.setOnClickListener(this);
        next.setOnClickListener(this);
        leibiao.setOnClickListener(this);
        linearLayout.setOnClickListener(this);

        fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.replace(R.id.activity_fragment, new MainActivity());
        fragmentTransaction.commit();

    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe
    public void getMusic(MusicListEvent musicListEvent) {
        musicBeanList = musicListEvent.getMusicBeanList();
        musicBean = musicBeanList.get(musicListEvent.getPostion());
        singName.setText(musicBean.getMusicName());
        singerName.setText(musicBean.getSingerName());
        netTool.getImage(musicBean.getSingerPic(), singPic);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getMusicDeatil2(MusicBeanListBean musicBeanListBean) {
        List<MusicBean> musicBeanList = musicBeanListBean.getMusicBeen();
        int position = musicBeanListBean.getPosition();
        singName.setText(musicBeanList.get(position).getMusicName());
        singerName.setText(musicBeanList.get(position).getSingerName());
        netTool.getImage(musicBeanList.get(position).getBigpic(), singPic);

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getMusicInfo(MusicBean musicBean) {
        singName.setText(musicBean.getMusicName());
        singerName.setText(musicBean.getSingerName());
        netTool.getImage(musicBean.getSingerPic(), singPic);
    }

    @Override
    protected void initData() {
        //启动就把音乐播放服务启动起来
        Intent playServiceIntent = new Intent(this, com.example.dllo.baidumusic.service.PlayService.class);
        startService(playServiceIntent);


        bindService(playServiceIntent, conn, BIND_AUTO_CREATE);

        IntentFilter filter = new IntentFilter();
        filter.addAction(PlayService.ACTION_PROGRESS);
        registerReceiver(mReceiver, filter);


    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.main_linerlayout:
                Intent intent = new Intent(this, PlayMusicAcyivity.class);
                startActivity(intent);
                overridePendingTransition(R.anim.anim_in, R.anim.anim_out);
                break;
            case R.id.paly_next:
                NextEvent nextEvent = new NextEvent();
                EventBus.getDefault().post(nextEvent);
                break;
            case R.id.play_liebiao:
                ShowPopWindow();
                break;
            case R.id.music_libary_paly:
                AskState askState = new AskState();
                EventBus.getDefault().post(askState);
                CheckBox checkBox = new CheckBox(this);
                checkBox.setBackgroundResource(R.mipmap.zanting_aaa);
                break;


        }

    }

    public static void getManager(Fragment fragment) {
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        transaction.add(R.id.activity_fragment, fragment).addToBackStack(null).commit();
    }

    //正在播放列表
    private void ShowPopWindow() {
        View view = LayoutInflater.from(NewActivity.this).inflate(R.layout.activity_new, null);
        View popView = LayoutInflater.from(this).inflate(R.layout.activity_liebiao, null);

        ImageButton imageButton = (ImageButton) popView.findViewById(R.id.play_pop_only);
        ListView listView = (ListView) popView.findViewById(R.id.liebiao_listview);
        ImageButton fanjui = (ImageButton) popView.findViewById(R.id.liebiao_fanhui);

        ListPopAdapter popListAdapter = new ListPopAdapter(getApplicationContext());

        popListAdapter.setMusicBean(musicBeanList);
        listView.setAdapter(popListAdapter);
        imageButton.setOnClickListener(this);
        fanjui.setOnClickListener(this);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
               EventBus.getDefault().post(new MusicListEvent(position,musicBeanList));
            }
        });
        final PopupWindow popupWindow = new PopupWindow(popView, ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        popupWindow.setAnimationStyle(R.style.AppTheme);
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(false);

        View.OnClickListener listener = new View.OnClickListener() {
            public void onClick(View v) {
                switch (v.getId()) {
//                    case R.id.play_pop_only:
//
//                        break;
                    case R.id.liebiao_fanhui:
                        popupWindow.dismiss();

                        break;

                }
                popupWindow.dismiss();
            }
        };
        ColorDrawable drawable = new ColorDrawable(0x99999999);
        popupWindow.setBackgroundDrawable(drawable);
        popupWindow.showAtLocation(view, 1 | 1, 0, 0);

    }


    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            switch (action) {
                case PlayService.ACTION_PROGRESS:
                    int progress = intent.getIntExtra(PlayService.KEY_PRORESS, 0);
                    seekBar.setProgress(progress);
                    break;

            }
        }
    };


    public void onBackPressed(View v) {
        new AlertDialog.Builder(this).setTitle("确认退出吗？")
                .setIcon(android.R.drawable.ic_dialog_info)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        NewActivity.this.finish();
                    }
                })
                .setNegativeButton("返回", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        Toast.makeText(getApplicationContext(), "你点击了返回键", Toast.LENGTH_LONG).show();
                    }
                }).show();
    }

}